package com.yehebl.orm.util;

import com.yehebl.orm.data.lambda.PropertyFun;

import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Method;


/**
 * 通过lambda表达式获取属性名
 */
public class LambdaUtil {

	/**
	 *  获取属性名
	 */
	public static <T,R>String getPropertyName(PropertyFun<T, R> column) {
		try {

			Method method = column.getClass().getDeclaredMethod("writeReplace");
			method.setAccessible(Boolean.TRUE);
			SerializedLambda serializedLambda = (SerializedLambda) method.invoke(column);
			String getter = serializedLambda.getImplMethodName();
			if(getter.startsWith("get")) {
				return upperFirst(getter.substring(3));
			}else if(getter.startsWith("is")) {
				return upperFirst(getter.substring(2));
			}
			return null;
		} catch (Exception e) {
			throw new RuntimeException("属性找不到");
		}
	}

	public static String upperFirst(String fieldName) {
		if(fieldName.length()==1) {
			return fieldName.toLowerCase();
		}
		return  fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1);
	}

}
